package com.duqc.zk.service.impl;

import com.duqc.zk.dto.ZkSeckillDTO;
import com.duqc.zk.mapper.ZkSeckillMapper;
import com.duqc.zk.service.ZkSeckillService;
import com.duqc.zk.utils.CommodityThread;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ZkSeckillServiceImpl
 * @Description TODO
 * @Author duqc
 * @Date 2021/5/13
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ZkSeckillServiceImpl implements ZkSeckillService {

    private final ZkSeckillMapper zkSeckillMapper;

    @Override
    public boolean purchaseCommodityInfo(String commodityId, Integer number) {
        //先查询数据库中商品的数量
        ZkSeckillDTO zkSeckill = this.zkSeckillMapper.purchaseCommodityInfo(commodityId);
        //判断商品数量是否大于0，或者购买的数量大于库存
        Integer count = zkSeckill.getNumber();
        if (count <= 0) {
            log.info("商品[ " + zkSeckill.getCommodityName() + " ]库存为0");
            return false;
        }
        if (number > count) {
            log.info("商品[ " + zkSeckill.getCommodityName() + " ]库存不足");
            return false;
        }
        count -= number;
        zkSeckill.setNumber(count);
        boolean bool = this.zkSeckillMapper.updateById(zkSeckill);
        if (bool) {
            log.info("购买商品[ " + zkSeckill.getCommodityName() + " ]成功,数量为：" + number);
        }
        return bool;
    }

//    /**
//     * 多线程
//     *
//     * @param args
//     */
//    public static void main(String[] args) {
//        //请求地址
//        String url = "http://localhost:8081/zk/purchase";
//        //请求参数
//        Map<String, String> map = new HashMap<>();
//        map.put("commodityId", "28059decb3b811eb8ebd2c16dba0d45a");
//        map.put("number", "1");
//        for (int i = 0; i < 10; i++) {
//            CommodityThread commodityThread = new CommodityThread(url, map);
//            commodityThread.start();
//        }
//    }

    /**
     * 多台服务器
     * @param args
     */
    public static void main(String[] args) {
        //请求地址
        String url = "http://localhost:%s/zk/purchase/curator";
        //请求参数，商品ID，数量
        Map<String, String> map = new HashMap<>();
        map.put("commodityId", "28059decb3b811eb8ebd2c16dba0d45a");
        map.put("number", "1");
        //创建10个线程通过HttpClient进行发送请求，测试
        for (int i = 0; i < 3; i++) {
            //8081、8082交替请求，每个服务器处理5个请求
            String port = "8081";
            CommodityThread commodityThread = new CommodityThread(String.format(url, port), map);
            commodityThread.start();
        }
    }

}
